package cn.wolfcode.luowowo.article.service.impl;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.Region;
import cn.wolfcode.luowowo.article.mapper.DestinationMapper;
import cn.wolfcode.luowowo.article.mapper.RegionMapper;
import cn.wolfcode.luowowo.article.query.RegionQueryObject;
import cn.wolfcode.luowowo.article.service.IRegionService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Created by admin on 2019/8/8.
 */
@Service
public class RegionServiceImpl implements IRegionService {

    @Autowired
    private RegionMapper regionMapper;

    @Autowired
    private DestinationMapper destinationMapper;

    // 查询地区列表
    @Override
    public PageInfo query(RegionQueryObject qo) {

        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Region> list = regionMapper.seleceForList(qo);

        return new PageInfo(list);
    }

    // 保存或修改地区
    @Override
    public void saveOrUpdate(Region region) {
        try {
            if (region.getId() == null) {
                regionMapper.insert(region);
            } else {
                regionMapper.updateByPrimaryKey(region);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 删除地区
    @Override
    public void deleteRegionById(Long id) {
        regionMapper.deleteByPrimaryKey(id);
    }

    // 修改地区热门状态
    @Override
    public void changeHotValueById(int hot, Long id) {
        regionMapper.updateHotValueById(hot, id);
    }

    // 查看关联地区
    @Override
    public List<Destination> getDestByRegionId(Long rid) {

        if (rid == -1) {
            return destinationMapper.selectHotDestByRegionId(1L);
        }

        // 查询出该地区关联的地区 id 字符串
        Region region = regionMapper.selectByPrimaryKey(rid);
        // 根据地区 id 字符串转换成的数组进行查询关联地区
        List<Destination> list = destinationMapper.selectDestinationByRid(region.getRefIds());
        return list;
    }

    @Override
    public List<Region> queryHotRegion() {
        return regionMapper.selectHotRegion();
    }
}
